<?php

namespace app\service;

use app\model\Node;
use app\model\Role;
use app\model\User;
use app\validate\UserValidate;
use think\exception\ValidateException;
use xiaodi\JWTAuth\Facade\Jwt;

class LoginService
{
    public function login($param)
    {
        try {

            validate(UserValidate::class)->scene('login')->check($param);
        } catch (ValidateException $e) {
            return dataReturn(-1, $e->getError());
        }

        $adminModel = new User();
        $info = $adminModel->getInfoByName($param['name']);

        if ($info['code'] != 0) {
            return dataReturn(-2, $info['msg']);
        }

        if (empty($info['data'])) {
            return dataReturn(-3, '用户名密码错误');
        }

        if (makePassword($param['password'], $info['data']['salt']) != $info['data']['password']) {
            return dataReturn(-4, '用户名密码错误');
        }

        $upData = [
            'last_login_ip' => request()->ip(),
            'last_login_time' => date('Y-m-d H:i:s'),
            'last_login_agent' => request()->header()['user-agent']
        ];

        // 查找权限菜单

        $res = $adminModel->updateInfoById($upData, $info['data']['id']);
        if ($res['code'] != 0) {
            return dataReturn(-5, $res['msg']);
        }

        $token = Jwt::token([
            'id' => $info['data']['id'],
            'name' => $info['data']['name'],
            'roleId' => $info['data']['role_id'],
            'avatar' => $info['data']['avatar']
        ]);

        $data = [
            'token' => (string)$token,
            'userInfo' => [
                'userId' => $info['data']['id'],
                'role_id' => $info['data']['role_id'],
                'userName' => $info['data']['name'],
                'avatar' => $info['data']['avatar']
            ]
        ];


        return dataReturn(0, '登录成功', $data);
    }

    public function getMenu($roleId, $userId)
    {
        $userModel = new User();
        $userInfo = $userModel->getUserById($userId)['data'];

        if ($roleId != 1) {
            $roleModel = new Role();
            $roleInfo = $roleModel->getRoleById($roleId)['data'];
            if (empty($roleInfo)) {
                return json(['code' => -8, 'data' => '', 'msg' => '该客服的角色不存在']);
            }
        } else {
            $roleInfo['role_node'] = '*';
        }

        $nodeModel = new Node();
        $menu = $nodeModel->getAuthNodeByIds($roleInfo['role_node'])['data'];
        $authNode = [];
        $menuMap = [];
        $authMenu = [];

        foreach ($menu as $key => $vo) {

            if ($vo['is_menu'] == 2 && !empty($vo['component'])) {

                if ($vo['flag'] == 'diy') {
                    $menuMap[] = ltrim($vo['web_path'], '/');
                } else {
                    $menuMap[] = $vo['component'];
                }

                $authMenu[] = $vo->toArray();
            }

            if ($vo['node_path'] == '#') continue;
            if ($roleInfo['role_node'] != '*') {
                $authNode[$vo['node_path']] = 1;
            }
        }

        if ($roleInfo['role_node'] == '*') {
            cache('user_auth_' . $userId, '*');
        } else {
            cache('user_auth_' . $userId, $authNode);
        }

        return dataReturn(0, 'success', [
            'menu' => $menuMap,
            'authMenu' => makeMenuTreeV2($authMenu),
            'id' => $userInfo['id'],
            'roleId' => $userInfo['role_id'],
            'name' => $userInfo['name'],
            'avatar' => $userInfo['avatar']
        ]);
    }
}